import 'package:cbec_app/components/base/base_nav_bar.dart';
import 'package:cbec_app/components/base/base_page.dart';
import 'package:cbec_app/components/common/count_down_timer.dart';
import 'package:cbec_app/components/popup/after_sales_popup.dart';
import 'package:cbec_app/pages/goods/controller/group_buying_item_detail_ctr.dart';
import 'package:cbec_app/utils/AppData.dart';
import 'package:cbec_app/utils/Tools.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';

import '../../../components/base/base_icon.dart';
import '../../../components/common/common_style.dart';
import '../../../components/common/consignee_info.dart';
import '../../../components/common/detail_item.dart';
import '../../../components/common/expand_collapse.dart';
import '../../../components/common/recommend.dart';
import '../../../components/goods/goods_info_item.dart';
import '../../../routes/routes.dart';
import '../../../utils/ThemeConfig.dart';

//团购页面
class GroupBuyingItemDetailPage extends GetView<GroupBuyingItemDetailCtr> {
  const GroupBuyingItemDetailPage({super.key});

  @override
  Widget build(context) {
    return GetBuilder<GroupBuyingItemDetailCtr>(
      builder: (controller) {
        return BasePage(
          title: '我的拼团',
          iconType: IconType.back,
          isShowPadding: true,
          children: [
            //地址
            addressWidget(),
            //成团Bar
            bookInfoBarWidget(),
            //商品列表 , 联系客服
            goodsInfoWidget(),
            //订单信息
            orderInfoWidget(),
            //个性推荐
            Recommend(location: "OrderDetail"),
            emptyMargin(70.h),
            bottomButtons(context),
          ],
        );
      },
    );
  }

  ///通用容器
  Widget _commonBox(Widget child) {
    return Container(
      margin: EdgeInsets.only(top: 10.h),
      decoration: BoxDecoration(borderRadius: BorderRadius.all(Radius.circular(8.h)), color: Colors.white),
      child: child,
    );
  }

  // 地址信息
  Widget addressWidget() {
    if (controller.bookInfo != null) {
      return ConsigneeInfo(
        isCanTap: false,
        receiveName: controller.bookInfo!.receiveName ?? '',
        receiveMobile: controller.bookInfo!.receiveMobile ?? '',
        receiveAddress: controller.bookInfo!.receiveAddress ?? '',
        receiveInfo: '',
        btnType: EditBtnType.none,
      );
    } else {
      return const SizedBox();
    }
  }

  // 成团 widget 样式
  Widget bookInfoBarWidget() {
    var bookStatus = controller.bookInfo?.bookStatus;
    // 拼团状态，0:拼团中;1:拼团成功;2:拼团失败
    if (bookStatus != null) {
      return InkWell(
        onTap: () {
          Get.toNamed(Routes.invitedFriends, arguments: controller.bookInfo?.bookId ?? '');
        },
        child: _commonBox(Row(
          mainAxisSize: MainAxisSize.max,
          children: [
            if (bookStatus == 0) ...[
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(8),
                  height: 44.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Row(
                        children: [
                          Text(
                            '在邀请${controller.bookInfo!.newPeople}人即可成团',
                            style: TextStyle(fontSize: 12, color: Tools.fromHex('#333333')),
                          ),
                          const SizedBox(
                            width: 5,
                          ),
                          const Text(
                            '距离结束还剩:',
                            style: TextStyle(fontSize: 12, color: ThemeConfig.themeColor),
                          ),
                          CountDownTimer(
                            timeStamp: DateTime.parse(controller.bookInfo!.ld ?? '').millisecondsSinceEpoch,
                            timeStyle: TimeStyle.hhmmss,
                            style: setTextStyle(12, FontWeight.w400, ThemeConfig.themeColor),
                            //取消订单自动返回
                            callback: () {
                              Get.back();
                            },
                          ),
                        ],
                      ),
                      Row(
                        children: [
                          ClipOval(
                            child: Image.network(
                              controller.bookInfo!.avatar ?? '',
                              width: 30,
                              height: 30,
                              fit: BoxFit.cover,
                            ),
                          ),
                          if (controller.bookInfo!.imgs != null && controller.bookInfo!.imgs!.isNotEmpty) ...[
                            avatarListWidget(),
                          ] else ...[
                            ClipOval(
                              child: Image.asset(
                                'assets/images/book_avatar.png',
                                width: 30,
                                height: 30,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                          Icon(
                            Icons.navigate_next,
                            color: Tools.fromHex('#333333'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              )
            ] else if (bookStatus == 1) ...[
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(8),
                  height: 44.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Text(
                        '拼团成功',
                        style: TextStyle(fontSize: 12, color: Tools.fromHex('#333333')),
                      ),
                      Row(
                        children: [
                          ClipOval(
                            child: Image.network(
                              controller.bookInfo!.avatar ?? '',
                              width: 30,
                              height: 30,
                              fit: BoxFit.cover,
                            ),
                          ),
                          if (controller.bookInfo!.imgs != null && controller.bookInfo!.imgs!.isNotEmpty) ...[
                            avatarListWidget(),
                          ] else ...[
                            ClipOval(
                              child: Image.asset(
                                'assets/images/book_avatar.png',
                                width: 30,
                                height: 30,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                          Icon(
                            Icons.navigate_next,
                            color: Tools.fromHex('#333333'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              )
            ] else ...[
              Expanded(
                child: Container(
                  padding: const EdgeInsets.all(8),
                  height: 44.h,
                  child: Row(
                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                    children: [
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: [
                          Text(
                            '拼团失败,退款已原路返回',
                            style: TextStyle(fontSize: 12, color: Tools.fromHex('#333333')),
                          ),
                          const SizedBox(
                            width: 5,
                          ),
                          Text(
                            controller.bookInfo!.cancelReason ?? '',
                            style: TextStyle(fontSize: 12, color: Tools.fromHex('#F83F2D')),
                          )
                        ],
                      ),
                      Row(
                        children: [
                          ClipOval(
                            child: Image.network(
                              controller.bookInfo!.avatar ?? '',
                              width: 30,
                              height: 30,
                              fit: BoxFit.cover,
                            ),
                          ),
                          if (controller.bookInfo!.imgs != null && controller.bookInfo!.imgs!.isNotEmpty) ...[
                            avatarListWidget(),
                          ] else ...[
                            ClipOval(
                              child: Image.asset(
                                'assets/images/book_avatar.png',
                                width: 30,
                                height: 30,
                                fit: BoxFit.cover,
                              ),
                            ),
                          ],
                          Icon(
                            Icons.navigate_next,
                            color: Tools.fromHex('#333333'),
                          ),
                        ],
                      )
                    ],
                  ),
                ),
              )
            ],
          ],
        )),
      );
    } else {
      return const SizedBox();
    }
  }

  // 商品信息
  Widget goodsInfoWidget() {
    bool isHaveGoodsList = controller.bookInfo != null && controller.bookInfo!.goodsInfo != null && controller.bookInfo!.goodsInfo!.isNotEmpty;
    if (isHaveGoodsList) {
      return _commonBox(ClipRRect(
        borderRadius: BorderRadius.all(Radius.circular(8.h)),
        child: Column(
          children: [
            controller.bookInfo!.goodsInfo!.isNotEmpty
                ? Column(
                    children: List.generate(controller.bookInfo!.goodsInfo!.length, (index) {
                      var item = controller.bookInfo!.goodsInfo![index];
                      return GoodsInfoItem(goodsInfo: item.toJson(), infoStyle: InfoStyle.settlement);
                    }),
                  )
                : const SizedBox(),
            //客服
            _customer(),
          ],
        ),
      ));
    } else {
      return const SizedBox();
    }
  }

  ///客服
  Widget _customer() {
    return InkWell(
      onTap: () {
        Get.toNamed(Routes.serviceSupportPage);
      },
      child: Container(
        height: 39.h,
        color: Colors.white,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            const BaseIcon(
              url: 'customer.png',
              size: 13,
            ),
            Padding(
              padding: EdgeInsets.only(left: 3.w),
              child: Text(
                '联系客服',
                style: setTextStyle(13, FontWeight.w500, ThemeConfig.mainTextColor),
              ),
            )
          ],
        ),
      ),
    );
  }

  //订单信息
  Widget orderInfoWidget() {
    if (controller.bookInfo != null) {
      return _commonBox(ExpandCollapse(
        heightFactor: 1,
        leftText: '订单信息',
        children: [
          DetailItem(
            label: '订单编号',
            content: '${controller.bookInfo!.sn ?? ''} 复制',
            contentStyle: ContentStyle.order,
            onTap: () {
              controller.copy(controller.bookInfo!.sn ?? '');
            },
          ),
          DetailItem(
            label: '支付方式',
            content: Tools.getPaymentType(controller.bookInfo!.payType ?? 0),
            contentStyle: ContentStyle.order,
          ),
          DetailItem(
            label: '实付款',
            content: '¥${controller.bookInfo!.priceOrder.toString()}',
            contentStyle: ContentStyle.order,
          ),
          DetailItem(
            label: '下单时间',
            content: controller.bookInfo!.cd ?? '',
            contentStyle: ContentStyle.order,
          ),
          DetailItem(
            label: '配送方式',
            content: Tools.getTransportType(controller.bookInfo!.shippingType ?? 0),
            contentStyle: ContentStyle.order,
          ),
        ],
      ));
    } else {
      return const SizedBox();
    }
  }

  // 参与评团的人头像
  Widget avatarListWidget() {
    return Row(
      mainAxisAlignment: MainAxisAlignment.start, // 根据需要设置对齐方式
      children: controller.bookInfo!.imgs!.map((img) {
        return Padding(
          padding: const EdgeInsets.only(right: 8.0), // 图片间距
          child: ClipOval(
            child: Image.network(
              img,
              width: 30,
              height: 30,
              fit: BoxFit.cover,
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget bottomButtons(BuildContext context) {
    var bookStatus = controller.bookInfo?.bookStatus;
    // 拼团状态，0:拼团中;1:拼团成功;2:拼团失败
    if (bookStatus == null) {
      return const SizedBox();
    } else {
      switch (bookStatus) {
        case 0: // 拼团中
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton(
                "邀请好友",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#F83F2D"),
                textColor: Tools.fromHex("#F83F2D"),
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  Get.toNamed(Routes.invitedFriends, arguments: controller.bookInfo?.bookId ?? '');
                },
              ),
            ],
          );
        case 1: // 拼团成功
          return Row(
            mainAxisAlignment: MainAxisAlignment.end,
            children: [
              solidButton(
                "申请售后",
                backgroundColor: Colors.white,
                borderColor: Tools.fromHex("#D7D7D7"),
                textColor: Colors.black,
                fontsize: 13,
                width: 72.w,
                height: 28.w,
                () {
                  List<Map<dynamic, dynamic>> goodsInfoListToMap = controller.bookInfo!.goodsInfo!.map((item) => item.toJson()).toList();
                  afterSalesPopup(context, goodsInfoListToMap, controller.bookInfo?.id ?? '', afterSaleStyle: 2);
                },
              ),
            ],
          );
        case 2: // 拼团失败
          return const SizedBox();
        default: // 添加一个默认处理
          return const SizedBox(); // 或者返回其他默认组件
      }
    }
  }
}
